<template>
  <div class="specialty">
    <LargerVersion @show="closeShow" v-if="show" :idx="imageIndex" :arrImg="imgList"></LargerVersion>
    <div class="release border-bottom">
      <div class="pic" v-show="!imgList.length">
        <span @click="upload($refs.upload)"><img src="~common/image/camera.png"></span>
      </div>
      <ul v-show="imgList.length">
        <li class="imgList" v-for="(item,index) in imgList">
          <img :src="item.path" @click="showLarger(index)">
          <span class="icon-close" @click="delUploadImg(index)"></span>
        </li>
        <li class="loading" v-show="upLoad">
          <img src="~common/image/loading.gif">
        </li>
        <li class="upload border-top border-bottom border-left-right" @click="upload($refs.upload)"
            v-if="imgList.length < 9">
          <i class="icon-add"></i>
          <input type="file" hidden class="upload-file" ref="upload"
                 @change="imgUpload($refs.upload)"
                 accept="image/*" capture="camera" multiple>
        </li>
      </ul>
    </div>
    <div class="info">
      <div class="input-box left-2 border-bottom">
        <label>名称</label>
        <input type="text" v-model="name" placeholder="最多输入30字" maxlength="30" ref="name"
               @keyup="holdInput('name',name)" @blur="out()" @focus="insinte(1,name)">
        <i class="icon-right icon-close" v-show="showCloseName" @click="name='',holdInput('name',name)"></i>
      </div>
      <div class="input-box left-2 border-bottom">
        <label>价格</label>
        <input type="text" v-model="price" placeholder="请输入价格描述" ref="price"
               @keyup="holdInput('price',price)" @blur="out()" @focus="insinte(2,price)">
        <i class="icon-right icon-close" v-show="showClosePrice" @click="price='',holdInput('price',price)"></i>
      </div>
      <div class="input-box left-3 border-bottom">
        <label>有效期</label>
        <input type="number" v-model="period" placeholder="请输入该发布信息有效天数" ref="period"
               @keyup="holdInput('period',period)" onkeydown="if(event.keyCode==13)event.keyCode=9"
               onKeypress="if((event.keyCode<48 || event.keyCode>57)) event.returnValue=false"
               oninput="if(value.length>3)value=value.slice(0,3)">
        <i class="icon-right icon-close" v-show="showCloseTime"
           @click="period='',holdInput('period',period)"></i>
      </div>
      <div class="input-box border-bottom">
        <label>发货方式</label>
        <div class="check-box">
          <span @click="_checkBox(1)"><i :class="{'check icon-dui': express,'notCheck' :!express}"></i>快递</span>
          <span @click="_checkBox(2)"><i :class="{'check icon-dui': pick,'notCheck' :!pick}"></i>自提</span>
        </div>
      </div>
      <div class="input-box border-bottom">
        <label>商品类型</label>
        <div class="check-box">
          <span @click="_checkBox(3)"><i :class="{'check icon-dui': cash,'notCheck' :!cash}"></i>现货</span>
          <span @click="_checkBox(4)"><i :class="{'check icon-dui': reserve,'notCheck' :!reserve}"></i>预定</span>
        </div>
      </div>
      <div class="describe">
        <label>商品描述</label>
        <textarea v-model="describe" placeholder="最多可输入1000个字" maxlength="1000"
                  ref="describe" @keyup="holdInput('describe',describe)"></textarea>
      </div>
      <div class="input-box address border-top border-bottom" @click="_address" v-if="address==null">
        <label>添加商品地址</label>
        <i class="icon-add"></i>
      </div>
      <router-link tag="div" :to="'/address/'+address.id" class="default border-top border-bottom" v-if="address">
        <p>
          <span>{{address.contact_name}}</span>
          <span>{{address.contact_phone}}</span>
          <span v-show="address.contact_wechat"><em class="icon-weixin"></em>{{address.contact_wechat}}</span>
        </p>
        <p>{{address.prov}}{{address.city}}{{address.area}}{{address.detailed_address}}</p>
        <i v-show="address.detailed_address" class="icon-xiangyou"></i>
      </router-link>
      <div class="btn" @click="submit">
        发布
      </div>
    </div>

    <address-view v-if="showAddress" title="新增商品地址" :item="item" @close="closeAddress()"
                  @setting="setting()"></address-view>
    <div id="allmap" style="display:none;"></div>

    <!--loading加载-->
    <Loading v-show="loading"></Loading>
  </div>
</template>

<script>
  import District from 'ydui-district/dist/jd_province_city_area_id';
  import {startUpload} from 'common/js/imgUpload'
  import {addGoods} from 'common/js/specialty'
  import {isLogin, isIdentity, lastContact, defaultContact} from 'common/js/user'
  import AddressView from 'components/address/add'
  import {mapGetters} from 'vuex'
  import LargerVersion from 'components/largerVersion/largerVersion'
  import Loading from 'components/loading/Loading'

  export default {
    data() {
      return {
        item: {},
        imgList: [],
        name: localStorage.getItem('name'), //名称
        price: localStorage.getItem('price'), //价格
        period: localStorage.getItem('period'), //有效期
        express: Boolean(localStorage.getItem('express')), //快递
        pick: Boolean(localStorage.getItem('pick')), //自提
        cash: Boolean(localStorage.getItem('cash')), //现货
        reserve: Boolean(localStorage.getItem('reserve')), //预定
        describe: localStorage.getItem('describe'), //描述信息
        showAddress: false,
        address: {},//地址
        place: '',//详细地址
        lat: '', //纬度
        lng: '', //经度
        goodsDeliver: '',// 提交发货方式
        goodsType: '', //提交商品类型
        imageIndex: 1, //查看大图找到对应张数
        show: false, //查看大图
        upLoad: false, //上传图片加载
        showCloseName: false, //显示清空产品名称
        showClosePrice: false,//显示清空价格
        showCloseTime: false,//显示清空有效时间
      }
    },
    computed: {
      ...mapGetters([
        'setAddress',
        'loading'
      ])
    },
    mounted() {
      document.title = '土特产发布';
      this.baiduMap();//百度地图
      this.recordInit(); //初始化记录用户录入
      this._defaultContact(); //初始化默认地址
      //判断是否登录
      isLogin().then(res => {
        if (Number(res.status) < 0) {
          this.$dialog.alert({
            mes: res.expand.info,
            callback: () => {
              this.$router.push('/login');
            }
          });
        }
      })
    },
    methods: {
      //获取焦点
      insinte(item, val) {
        if (val !== '') {
          switch (item) {
            case 1:
              this.showCloseName = true;
              break;
            case 2:
              this.showClosePrice = true;
              break;
          }
        }
      },
      //失去焦点
      out() {
        this.showCloseName = false;
        this.showClosePrice = false;
        this.showCloseTime = false;
      },
      //对焦有内容显示关闭
      _inputClose(val) {
        return false
      },
      //查看大图
      showLarger(idx) {
        this.imageIndex = idx;
        this.show = true;
      },
      //关闭查看大图
      closeShow() {
        this.show = false;
      },
      //删除上传图片
      delUploadImg(index) {
        this.$dialog.confirm({
          title: '删除该图片？',
          mes: '',
          opts: () => {
            this.imgList.splice(index, 1);
            var obj = JSON.stringify(this.imgList);
            localStorage.setItem("imgList", obj);
          }
        });
      },
      //保存后续操作
      setting() {
        this.showAddress = false;
        this._defaultContact();
      },
      //提交发布
      submit() {
        this.goodsDeliver = this._returnWay(this.express, this.pick);
        this.goodsType = this._returnWay(this.cash, this.reserve)
        if (!this.imgList.length) {
          this.$dialog.alert({mes: '请点击照相机图片上传产品照片'});
        } else if (this.name.match(/^\s+$/g) || this.name == null || this.name === '') {
          this.$dialog.toast({mes: '请输入产品名称', timeout: 1000,});
          this.$refs.name.focus();
        } else if (this.price.match(/^\s+$/g) || this.price === '' || this.price == null) {
          this.$dialog.toast({mes: '请输入产品价格', timeout: 1000,});
          this.$refs.price.focus();
        } else if (this.period === '' || this.period == null) {
          this.$dialog.toast({mes: '请输入产品有效天数', timeout: 1000,});
          this.$refs.period.focus();
        } else if (this.goodsDeliver === '') {
          this.$dialog.toast({mes: '请勾选发货方式', timeout: 1000,});
        } else if (this.goodsType === '') {
          this.$dialog.toast({mes: '请勾选商品类型', timeout: 1000,});
        } else if (this.address == null) {
          this.$dialog.toast({mes: '请添加商品地址', timeout: 1000,});
          this.showAddress = true;
        } else {
          var imgId = ''//产品图片
          for (var i = 0; i < this.imgList.length; i++) {
            imgId += this.imgList[i].id + ',';
          }
          var deliver = '';
          addGoods({
            "phpsid": localStorage.getItem('token'),//session_id
            "goods_validity": this.period,//发布有效日期
            "goods_name": this.name,//土特产名称
            "goods_price": this.price,//土特产价格
            "goods_deliver": this.goodsDeliver, //1-快递，2-自提
            "goods_type": this.goodsType,//1-现货，2-预定
            "goods_desc": this.describe,//产品描述
            "contact_id": this.address.id,//联系id
            "images_id": imgId.substr(0, imgId.length - 1),//图片id
            "goods_add_place": this.place,//发布地址（当前位置）
            "long": this.lng,//经度
            "lat": this.lat,//纬度
          }).then(res => {
            console.log(res)
            if (res.status === 1) {
              this.emptyRecord();
              this.$dialog.toast({
                mes: '发布成功！',
                timeout: 1000,
                callback: () => {
                  this.$router.push('/specialtyDetails/' + res.data);
                }
              });
            } else if (res.status < 0) {
              this.$dialog.toast({
                mes: res.expand.info,
                timeout: 1000
              });
            }
          })
        }
      },
      //返回方式
      _returnWay(item1, item2) {
        var type = '';
        if (item1) {
          type = '0'
        }
        if (item2) {
          type = '1'
        }
        if (item1 && item2) {
          type = '0,1'
        }
        return type;
      },
      //添加地址
      _address() {
        this.showAddress = true;
      },
      //关闭地址添加
      closeAddress() {
        this.showAddress = false;
      },
      //初始化默认地址
      _defaultContact() {
        defaultContact().then(res => {
          if (res.status === 1) {
            if (this.setAddress.id) {
              this.address = this.setAddress;
            } else {
              this.address = res.data;
            }
          }
        })
      },
      //选中图片上传
      imgUpload(item) {
        this.upLoad = true;
        startUpload(item.files[0]).then(res => {
          if (res.status === 1) {
            this.imgList.push({
              id: res.img_id,
              path: res.path
            })
            this.upLoad = false;
            var obj = JSON.stringify(this.imgList);
            localStorage.setItem("imgList", obj);
          } else if (res.status < 0) {
            this.$dialog.alert({mes: res.expand.info});
          } else {
            this.$dialog.alert({mes: res.info});
          }
        })
      },
      //点击上传图片
      upload(item) {
        //判断是否是苹果，如果是删除capture属性
        var ua = navigator.userAgent.toLowerCase();
        var isIos = (ua.indexOf('iphone') != -1) || (ua.indexOf('ipad') != -1);
        if (isIos) {
          item.removeAttribute('capture')
        }
        //点击input上传
        item.click();
      },
      //保存用户输入
      holdInput(key, val, type) {
        localStorage.setItem(key, val);
        switch (key) {
          case 'name':
            if (val !== '') {
              this.showCloseName = true;
            } else {
              this.showCloseName = false;
            }
            break;
          case 'price':
            if (val !== '') {
              this.showClosePrice = true;
            } else {
              this.showClosePrice = false;
            }
        }
      },
      //复选框,发货方式，商品类型
      _checkBox(type) {
        switch (type) {
          case 1:
            this.express = !this.express;
            if (this.express) {
              localStorage.setItem('express', true);
            } else {
              localStorage.setItem('express', '');
            }
            break;
          case 2:
            this.pick = !this.pick;
            if (this.pick) {
              localStorage.setItem('pick', true);
            } else {
              localStorage.setItem('pick', '');
            }
            break;
          case 3:
            this.cash = !this.cash;
            if (this.cash) {
              localStorage.setItem('cash', true);
            } else {
              localStorage.setItem('cash', '');
            }
            break;
          case 4:
            this.reserve = !this.reserve;
            if (this.reserve) {
              localStorage.setItem('reserve', true);
            } else {
              localStorage.setItem('reserve', '');
            }
            break;
        }
      },
      //清空记录
      emptyRecord() {
        var obj = JSON.stringify([]);
        localStorage.setItem("imgList", obj);
        localStorage.setItem('name', '');
        localStorage.setItem('price', '');
        localStorage.setItem('period', '');
        localStorage.setItem('express', true);
        localStorage.setItem('pick', '');
        localStorage.setItem('cash', true);
        localStorage.setItem('reserve', '');
        localStorage.setItem('describe', '');
      },
      //记录初始化
      recordInit() {
        //图片数组里面有图片
        if (JSON.parse(localStorage.getItem("imgList")) != null) {
          this.imgList = JSON.parse(localStorage.getItem("imgList"));
        }
        this._fill(localStorage.getItem('name'));
        this._fill(localStorage.getItem('price'));
        this._fill(localStorage.getItem('period'));
        this._fill(localStorage.getItem('express'), 1);
        this._fill(localStorage.getItem('pick'), 2);
        this._fill(localStorage.getItem('cash'), 3);
        this._fill(localStorage.getItem('reserve'), 4);
      },
      //补空
      _fill(data, type) {
        if (data == null) {
          switch (type) {
            case 1:
              return localStorage.setItem('express', true);
            case 2:
              return localStorage.setItem('pick', '');
            case 3:
              return localStorage.setItem('cash', true);
            case 4:
              return localStorage.setItem('pick', '');
            default:
              return ''
          }
        }
      },
      //百度地图
      baiduMap() {
        var map = new BMap.Map("allmap");
        var _this = this;
        var geolocation = new BMap.Geolocation();
        this.$store.dispatch('showLoading');
        geolocation.getCurrentPosition(function (r) {
          if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            var point = new BMap.Point(r.point.lng, r.point.lat);//用所定位的经纬度查找所在地省市街道等信息
            var gc = new BMap.Geocoder();
            gc.getLocation(point, function (rs) {
              _this.$store.dispatch('hideLoading');
              _this.place = rs.address; //详细地址
              _this.lat = rs.point.lat; //维度
              _this.lng = rs.point.lng; //经度
            });
          }
        })
      }
    },
    components: {
      AddressView,
      LargerVersion,
      Loading
    }
  }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  @import "~common/stylus/variable"
  .specialty
    color: $color-text;
    .left-2
      padding: 0 1rem 0 2rem;
    .left-3
      padding: 0 1rem 0 2.5rem;
    .release
      min-height: 3.8rem;
      background-repeat: no-repeat;
      background-size: 2.13rem;
      background-position: center center;
      .pic
        min-height: 3.8rem;
        text-align: center;
        display: flex;
        justify-content: center;
        align-items: center;
        span
          display: inline-block;
        img
          width: 2.13rem;
      .release-box
        background: $background-f;
        min-height: 3.8rem;
      ul
        padding: .4rem .31rem;
        overflow: hidden;
        background: $background-f;
        li
          float: left;
          margin: .19rem;
          img
            display: block;
            width: 3rem;
            height: 3rem;
        .upload
          width: 3rem;
          font-size: 1.57rem;
          text-align: center;
          line-height: 3rem;
          color: $color-code;
    .info
      padding: 0 .5rem .5rem .5rem;
      background: $background-f;
    .input-box
      position: relative;
      height: 1.32rem;
      font-size: .4rem;
      color: $color-text;
      label
        position: absolute;
        top: 0;
        left: 0;
        line-height: 1.32rem;
        font-size: .45rem;
      input
        width: 100%;
        font-size: .45rem;
        line-height: 1.32rem;
        color: $color-text;
      input:
      :-webkit-input-placeholder
        color: $color-code;
      .icon-close
        position: absolute;
        top: 0;
        right: 0;
        width: 1rem;
        text-align: center;
        line-height: 1.32rem;
      .check-box
        line-height: 1.32rem;
        padding-left: 3rem;
        span
          margin-left: .56rem;
        .check
          display: inline-block;
          width: .34rem;
          height: .34rem;
          border: $border-check;
          border-radius: 2px;
          margin-right: .2rem;
          font-size: .1rem;
          overflow: hidden;
          color: $color-a;
          text-align: center;
        .notCheck
          display: inline-block;
          width: .34rem;
          height: .34rem;
          border: $border;
          border-radius: 2px;
          margin-right: .2rem;
    .default
      position: relative;
      line-height: .8rem;
      color: $color-text;
      font-size: .4rem;
      .icon-xiangyou
        position: absolute;
        top: 0;
        right: 0;
        line-height: 1.6rem;
        font-size: .55rem;
      .icon-weixin
        font-size: .4rem;

        margin-left: .4rem;
    .address
      .icon-add
        position: absolute;
        top: 0;
        right: 0;
        width: 1rem;
        text-align: center;
        font-size: .52rem;
        line-height: 1.32rem;

    .describe
      padding-bottom: .45rem;
      label
        display: block;
        width: 100%;
        line-height: 1.32rem;
        font-size: .45rem;
      textarea
        width: 100%;
        size: none;
        height: 3.15rem;
        border: $border;
        padding: 1%;
        color: $color-text;
        font-size: .38rem;
    .imgList
      position: relative;
      .icon-close
        position: absolute;
        top: -.2rem;
        right: -.2rem;
        background: $color-main;
        color: $color;
        padding: .1rem;
        border-radius: 50%;

  .btn
    line-height: 1.4rem;
    background: $background-btn;
    text-align: center;
    font-size: .5rem;
    margin-top: .5rem;
    color: $color;
</style>
